<template>
    <van-swipe :autoplay="3000" lazy-render>
        <van-swipe-item v-for="image in product.thumbs_text" :key="image">
            <van-image
                width="100%"
                height="500"
                fit="cover"
                :src="image"
            />
        </van-swipe-item>
    </van-swipe>

    <div class="detailbox">
        <div class="box">
            <div class="left">
                <span v-if="product.live_price">￥{{ product.live_price }}</span>
                <span :class="product.live_price ? 'product_price' : ''">￥{{ product.price }}</span>
            </div>
            <div class="right">
                <div class="sales">{{ product.buy_count }} 人付款</div>
                <div class="region">{{ product.region_text }}</div>
            </div>
        </div>

        <h4>{{ product.name }}</h4>
    </div>
    
    <div class="allkbox"></div>

    <!-- 商品规格 -->
    <div class="info_choice">
        <!-- Sku 商品规格 -->
        <div class="commodity" @click="SkuShow = true">
            <div class="opt">
                <div class="title wanl-gray">选择</div>
                <div class="option">
                    <div class="selected">
                        <div v-if="Object.getOwnPropertyNames(SelectedProp).length === 0">
                            <span>选择</span>
                            <span v-for="(val,index) in props" :key="index">{{ val }}</span>
                        </div>

                        <div v-else>
                            <span>已选择</span>
                            <span v-for="(val,index) in Object.values(SelectedProp)" :key="index">{{ val }}</span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="wanl-gray">
                <img src="/assets/images/go.png" />
            </div>
        </div>
        <!-- 服务 -->
        <div class="commodity" @click="TipShow = true">
            <div class="opt">
                <div class="title wanl-gray">服务</div>
                <div class="option">
                    <div class="selected">
                        <div>
                            <span>7天无理由退款</span>
                            <span>·</span>
                            <span>24小时内发货</span>
                            <span>·</span>
                            <span>假一赔十</span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="wanl-gray">
                <img src="/assets/images/go.png" />
            </div>
        </div>
    </div>

    <div class="allkbox"></div>

    <div class="allkbox"></div>

    <div class="comment" @click="ToCommentList">
        <div class="header">
            <div class="title">宝贝评价（{{ CommentCount }}）</div>
            <div class="rate">
                <div class="rate-text">好评率高达{{ ApplauseRate }}%</div>
                <div class="wanl-gray">
                    <img src="/assets/images/go.png" />
                </div>
            </div>
        </div>
        <div class="comment-list">
            <div class="item" v-for="item in CommentList" :key="item.id">
                <div class="user">
                    <div class="avatar">
                        <img :src="item.business.avatar_text" alt="">
                    </div>
                    <div class="nickname">
                        {{ item.business.nickname }}
                    </div>
                    <div class="rate">
                        <van-rate
                            v-model="item.rate"
                            :size="14"
                            color="#ffd21e"
                            void-icon="star"
                            void-color="#eee"
                            readonly
                        />
                    </div>
                </div>
                <div class="content">
                    {{ item.comment }}
                </div>
            </div>
        </div>
    </div>

    <div class="allkbox"></div>

    <div class="product-info">
        <div class="title-box">
            <div class="line"></div>
            <div class="title">产品详情</div>
        </div>

        <div class="content" v-html="product.content"></div>
    </div>

    <!-- 协议条款 -->
    <van-action-sheet v-model:show="TipShow" title="协议条款">
        <div class="ProductTip">
            一、我们如何使用信息 <br />
            二、我们如何共享信息<br />
            三、我们如何转让信息<br />
            四、我们如何公开披露信息<br />
            五、一般储存期限<br />
            六、我们如何确保您的信息安全<br />
            七、您能做什么<br />
            八、我们如何处理未成年人的个人信息<br />
            九、您的个人信息的存储地点<br />
            十、本隐私权政策不适用的范围<br />
            十一、本隐私权政策如何更新<br />
            十二、联系我们<br />
        </div>
    </van-action-sheet>

    <!-- SKU -->
    <van-sku
        ref="SkuRef"
        v-model="SkuShow"
        :sku="sku"
        :properties="properties"
        :goods="goods"
        :goods-id="product.id"
        @add-cart="OnAddCart"
        @buy-clicked="OnBuy"
        @sku-prop-selected="OnSelectedProp"
    >
        <template #sku-actions="props">
            <div class="van-sku-actions">
                <van-button square size="large" type="warning" @click="props.skuEventBus.emit('sku:addCart')">加入购物车</van-button>

                <!-- 直接触发 sku 内部事件，通过内部事件执行 onBuyClicked 回调 -->
                <van-button square size="large" type="danger" @click="props.skuEventBus.emit('sku:buy')">立即购买</van-button>
            </div>
        </template>
    </van-sku>

    <div style="height: 50px;"></div>


    <!-- 底部导航栏 -->
    <van-action-bar>
        <van-action-bar-icon icon="chat-o" text="客服" />
        <van-action-bar-icon icon="cart-o" text="购物车" :badge="product.cart_count" @click="ToCart" />
        <van-action-bar-icon icon="star" text="已收藏" color="#ff5000" @click="OnCollection" v-if="product.collection_status === true" />
        <van-action-bar-icon icon="star-o" text="收藏" @click="OnCollection" v-else />
        <van-action-bar-button type="danger" text="立即购买" @click="SkuShow = true" />
    </van-action-bar>
</template>

<script setup>
/* 
    商品规格组件
    安装指令：npm install vant-sku
*/
import VanSku from 'vant-sku';
import 'vant-sku/dist/index.css';

const { proxy } = getCurrentInstance();

const business = proxy.$business;

// 商品id
const proid = ref(proxy.$route.query.proid ? proxy.$route.query.proid : 0);

const product = ref({});

// 显示商品规格弹出层
const SkuShow = ref(false);
// 商品规格数据
const sku = ref({});
// 商品属性数据
const properties = ref([]);
// sku里的商品信息
const goods = ref({});
const SkuRef = ref({});

// 用户在前端选择规格
const SelectedProp = ref({});
// 该商品的规格名称
const props = ref(['商品规格']);
// 评价数据
const CommentList = ref([]);
// 好评率
const ApplauseRate = ref(0);
// 评价总数
const CommentCount = ref(0);

// 显示条款协议
const TipShow = ref(false);

onBeforeMount(() =>
{
    GetProductData();
});

const GetProductData = async () =>
{
    const params = {
        proid:proid.value
    }

    if(Object.getOwnPropertyNames(business.value).length > 0 && business.value.hasOwnProperty('id') === true)
    {
        params.busid = business.value.id;
    }

    const result = await proxy.$http.post('/product/info',params);

    if(result.code === 1)
    {
        product.value = result.data.product;
        CommentList.value = result.data.CommentData;
        CommentCount.value = result.data.CommentCount;
        ApplauseRate.value = result.data.ApplauseRate;

        CommentList.value.map(item => {
            item.rate = parseInt(item.rate);
        });

        sku.value = result.data.sku;
        properties.value = Object.values(result.data.properties);
        goods.value = {picture: product.value.thumb_text};
        props.value = result.data.props.length > 0 ? result.data.props : ['数量'];
    }else{
        proxy.$fail(result.msg,() => proxy.$router.back());
    }
}

// 加入购物车
const OnAddCart = async (SkuData) =>
{
    if(Object.getOwnPropertyNames(business.value).length === 0)
    {
        proxy.$confirm({
            title:'登录提示',
            message:'是否确认跳转到登录页？'
        }).then(() => {
            proxy.$cookies.set('action','login');

            proxy.$router.push({path:'/business/login'});
        }).catch((err) => {});

        return false;
    }

    // 如果有商品规格，但是用户不选择
    if(properties.value.length > 0 && !SkuData.selectedSkuComb)
    {
        proxy.$fail('请选择商品规格');

        return false;
    }

    const SelectedNum = SkuData.selectedNum ? SkuData.selectedNum : 0;

    if(SelectedNum <= 0)
    {
        proxy.$fail('商品数量不能小于1');
    }

    // 选择的属性id
    const relationids = [];

    if(properties.value.length > 0)
    {
        for(let item of SkuData.selectedSkuComb.properties)
        {
            relationids.push(item.v[0].id);
        }
    }

    // 组装插入数据
    const params = {
        busid:business.value.id,
        relationids:relationids.join(','),
        proid:proid.value,
        nums: SelectedNum,
    }

    const result = await proxy.$http.post('/cart/add',params);

    if(result.code === 1)
    {
        // 关闭Sku弹出层
        SkuShow.value = false;

        // 把购物车数量更新
        product.value.cart_count = result.data;

        proxy.$confirm({
            title:'加入购物车成功',
            message:'是否跳转购物车进行结算？'
        }).then(() =>
        {
            proxy.$router.push({
                path:'/cart',
                query:{action:'info'}
            });
        }).catch(() => {});
    }else{
        proxy.$fail(result.msg);
    }
}

// 立即购买
const OnBuy = (SkuData) =>
{
    if(Object.getOwnPropertyNames(business.value).length === 0)
    {
        proxy.$confirm({
            title:'登录提示',
            message:'是否确认跳转到登录页？'
        }).then(() => {
            proxy.$cookies.set('action','login');

            proxy.$router.push({path:'/business/login'});
        }).catch((err) => {});

        return false;
    }

    // 如果有商品规格，但是用户不选择
    if(properties.value.length > 0 && !SkuData.selectedSkuComb)
    {
        proxy.$fail('请选择商品规格');

        return false;
    }

    const SelectedNum = SkuData?.selectedNum ? SkuData.selectedNum : 0;

    if(SelectedNum <= 0)
    {
        proxy.$fail('商品数量不能小于1');

        return false;
    }

    const relations = [];

    // 获取商品价格
    let total = product.value.live_price ? product.value.live_price : product.value.price;

    total = parseFloat(total);

    if(properties.value.length > 0 && SkuData.selectedSkuComb)
    {
        for(let item of SkuData.selectedSkuComb.properties)
        {
            if(item?.v[0].id)
            {
                relations.push({
                    title:item.k,
                    value:item.v[0].name,
                    price:parseFloat((item.v[0].price / 100).toFixed(2))
                });

                total += (item.v[0].price / 100);
            }
        }
    }

    // 获取当前商品是否直播商品
    const type = product.value.live_price ? 'live' : 'product';

    const data = [
        {
            proid:product.value.id,
            nums: SelectedNum,
            product:product.value,
            price:total,
            total:(total * SelectedNum).toFixed(2),
            attrs:relations, // 商品规格
            type
        }
    ];

    proxy.$cart.value = data;

    proxy.$router.push('/cart/confirm');
}

// 选择属性
const OnSelectedProp = ({propValue}) =>
{
    SelectedProp.value[propValue.skuKeyStr] = propValue.name;
}

// 去购物车页面
const ToCart = () =>
{
    proxy.$router.push({
        path:'/cart',
        query:{action:'info'}
    });
}

// 收藏商品
const OnCollection = async () =>
{
    if(Object.getOwnPropertyNames(business.value).length === 0)
    {
        proxy.$confirm({
            title:'登录提示',
            message:'是否确认跳转到登录页？'
        }).then(() => {
            proxy.$cookies.set('action','login');

            proxy.$router.push({path:'/business/login'});
        }).catch((err) => {});

        return false;
    }

    const params = {
        busid:business.value.id,
        proid:proid.value
    }

    const result = await proxy.$http.post('/product/collection',params);

    if(result.code === 1)
    {
        product.value.collection_status = result.data.action;
    }else{
        proxy.$fail(result.msg);
    }
}
</script>

<style scoped>
@import url('/assets/css/ProductInfo.css');
</style>